package org.raymond.iworks.study.basic.thread.concurrenthashmap;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;

@Slf4j
public class Demo2 {
    public static void main(String[] args) {
        int threadNum = 1;
        for(int i=0; i<5; i++){
            log.info("{}-{}", i, testAdd(threadNum));
        }
        log.info("------");
        threadNum = 5;
        for(int i=0; i<5; i++){
            log.info("{}-{}", i, testAdd(threadNum));
        }
    }

    static class TestTask implements Runnable {
        private ConcurrentHashMap<Integer, Integer> map;

        public TestTask(ConcurrentHashMap<Integer, Integer> map){
            this.map = map;
        }

        @Override
        public void run() {
            for(int i=0; i<100; i++){
                // synchronized (map) {
                    map.put(1, map.get(1) + 1);
                // }
            }
        }
    }

    private static int testAdd(int threadNum){
        ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
        map.put(1, 0);
        ExecutorService es = Executors.newCachedThreadPool();
        for(int i=0; i<threadNum; i++){
            es.execute(new TestTask(map));
        }
        //es.shutdown();
        try {
            es.awaitTermination(20, TimeUnit.MICROSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            es.shutdown();
        }
        return map.get(1);
    }
}
